// @file          FlyerProcessor.groovy
// @author        Mac Radigan
// @description 

package ycoa.flyer

import ycoa.configuration.YCOAConfiguration
import sys.xml.XMLUtilities
import org.w3c.dom.Element
import org.w3c.dom.Document
import org.apache.log4j.Logger

public class FlyerProcessor {

  static Logger log = Logger.getRootLogger(FlyerProcessor.class)

  private int size
  private configuration = YCOAConfiguration.getInstance()
  private config = YCOAConfiguration.getConfiguration()
  private String root = null

  public FlyerProcessor() {
    root = configuration.getRoot()
  }

  public void setSize(int size) {
    this.size = size
  }

  private Document processRawToOOXML(xmlRaw, xmlTemplate) {
    //
    // RAW to DATA
    //
    def xslDataFile = "${root}/modules/flyer/xsl/dataset_to_reportdata.xsl"
    def xslData = XMLUtilities.newDocument( new File(xslDataFile).text )
    def xmlData = XMLUtilities.xslt(xmlRaw, xslData)
    //println "=== DATA ==="
    //
    // RAW to DATA
    //
    def xslTemplateFile = "${root}/modules/flyer/xsl/report_to_wordxsl.xsl"
    def xslTemplate = XMLUtilities.newDocument( new File(xslTemplateFile).text )
    def xslReport = XMLUtilities.xslt(xmlTemplate, xslTemplate)
    //println "=== XSL ==="
    //
    // DATA to OOXML
    //
    def xmlFlyer = XMLUtilities.xslt(xmlData, xslReport)
    //println "=== FLYER ==="
    return xmlFlyer
  }

  private void importSubreport(report, node, subreport) {
    def xpath = "//dataset"
    def xpathResult = XMLUtilities.findNodes(subreport, xpath)
    if( xpathResult.getSnapshotLength() > 0 ) {
      def subreportNode = (org.w3c.dom.Node)xpathResult.snapshotItem(0)
      def importedSubreportNode = (Element)report.importNode(subreportNode, true)
      def rootElement = report.getDocumentElement()
      rootElement.setAttribute( "xmlns:w", "http://schemas.microsoft.com/office/word/2003/wordml" )
      rootElement.setAttribute( "xmlns:v", "urn:schemas-microsoft-com:vml"  )
      rootElement.setAttribute( "xmlns:w10", "urn:schemas-microsoft-com:office:word"  )
      rootElement.setAttribute( "xmlns:sl", "http://schemas.microsoft.com/schemaLibrary/2003/core" )
      rootElement.setAttribute( "xmlns:aml", "http://schemas.microsoft.com/aml/2001/core" )
      rootElement.setAttribute( "xmlns:wx", "http://schemas.microsoft.com/office/word/2003/auxHint" )
      rootElement.setAttribute( "xmlns:o", "urn:schemas-microsoft-com:office:office" )
      rootElement.setAttribute( "xmlns:dt", "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" )
      rootElement.setAttribute( "xmlns:st1", "urn:schemas-microsoft-com:office:smarttags" )
      node.replaceChild( importedSubreportNode, node.getFirstChild() )
    }
  }

  private String process(xmlRaw, xmlTemplate) {
    // process
    def templateFile = "${root}/modules/flyer/xml/FlyerOutline.wordml-template.xml" 
    xmlTemplate = XMLUtilities.newDocument( new File(templateFile).text )  // duplicate definition
    def xmlFlyer = processRawToOOXML(xmlRaw, xmlTemplate)

    // embed flyer panels
    def xpathResult = XMLUtilities.findNodes(xmlFlyer, '//logicXInclude')
    for (int nodeIndex = 0; nodeIndex < xpathResult.getSnapshotLength(); nodeIndex++) {
      def node = (org.w3c.dom.Node)xpathResult.snapshotItem(nodeIndex)
      def nodeMapAttributes = node.getAttributes()
      for(int attributeIndex=0; attributeIndex < nodeMapAttributes.getLength(); attributeIndex++) {
        def attribute = nodeMapAttributes.item(attributeIndex)
        if( attribute.getNodeName().equals("reportid") ) {
          def panel = null
          if( attribute.getNodeValue().equals("FlyerPanelA") ) {
            panel = getPanel(flyerid, 'A')
          }
          if( attribute.getNodeValue().equals("FlyerPanelB") ) {
            panel = getPanel(flyerid, 'B')
          }
          if( attribute.getNodeValue().equals("FlyerPanelC") ) {
            panel = getPanel(flyerid, 'C')
          }
          if( attribute.getNodeValue().equals("FlyerPanelD") ) {
            panel = getPanel(flyerid, 'D')
          }
          xmlRaw = XMLUtilities.newDocument( panel )
          templateFile = "${root}/modules/flyer/xml/FlyerPanel.wordml-template.xml" 
          xmlTemplate = XMLUtilities.newDocument( new File(templateFile).text )
          def xmlSubFlyer = processRawToOOXML(xmlRaw, xmlTemplate)
          importSubreport(xmlFlyer, node, xmlSubFlyer)
        }
      }
    }

    // apply formatting
    templateFile = "${root}/modules/flyer/xsl/format_to_wordxsl.xsl"
    xmlTemplate = XMLUtilities.newDocument( new File(templateFile).text )
    formatFile = "${root}/modules/flyer/xml/FlyerFormat${size}.wordml-format.xml"
    xmlFormat = XMLUtilities.newDocument( new File(formatFile).text )
    def xslFormat = XMLUtilities.xslt(xmlFormat, xmlTemplate)
    def xmlFormattedFlyer = XMLUtilities.xslt(xmlFlyer, xslFormat)

   //
   // print result
   //
   //println "=== FLYER ==="
   data = XMLUtilities.parseToString(xmlFormattedFlyer)
   response.setContentType("text/xml")
   response.addHeader("Content-disposition", "attachment; filename=flyer-${flyername}.xml")
   println data
  }

}

/* *EOF* */
